<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;
use think\Db\Query;

class Storage extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    protected $searchFields = ['id', 'code'];
    public function __construct()
    {
        parent::__construct();
        $this->model = model("Depot.Storage");
        $this->SupplierModel = model("Depot.Supplier");
        $this->ProductModel = model("Product.Product");
        $this->DepotProductModel = model('Depot.Product');
        $this->RegionModel = model('Region');
        $this->BackModel = model('Depot.Back');
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    public function index()
    {
        // $list = $this->model
        // ->with(['supplier'])
        // ->select(); //查询数据
        // halt(collection($list)->toArray());
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // halt($where);

            $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit); //查询数据
            // halt(collection($list)->toArray());
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    // 供应商
    public function supplier()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->SupplierModel
                ->with(['provinces', 'citys', 'districts'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->SupplierModel
                ->with(['provinces', 'citys', 'districts'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->ProductModel
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->ProductModel
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            $productList = json_decode($params['product'], true);
            // halt($productList);
            // exit;

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();
            // 组装数据
            $data = [
                'code' => build_code('SU'),
                'supplierid' => $params['supplierid'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => 0
            ];
            $storageStatus = $this->model->validate('common/Depot/Storage')->save($data);
            if ($storageStatus === false) {
                $this->error($this->model->getError());
                exit;
            }
            // 添加商品的数据
            $productData = [];
            foreach ($productList as $item) {
                $productData[] = [
                    'storageid' => $this->model->id,
                    'proid' => $item['id'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];
            }
            // halt($productData);
            $productStatus = $this->DepotProductModel->validate('common/Depot/Product')->saveAll($productData);
            if ($productStatus === false) {
                $this->model->rollback();
                $this->error($this->model->getError());
                exit;
            }
            if ($productStatus === false || $storageStatus === false) {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error(__('添加失败'));
                exit;
            } else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success(__('添加成功'));
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->with(['supplier'])->find($ids);

        $ProductList = $this->DepotProductModel->with(['products', 'storage'])->where('storageid', $ids)->select();
        if (!$ProductList) {
            $this->error(__('该商品不存在，请重新选择'));
        }

        if (!$row) {
            $this->error(__('该入库单不存在'));
            exit;
        }
        $supplier = $this->SupplierModel->with(['provinces', 'citys', 'districts'])->where('id', $row['supplierid'])->find();
        if ($supplier) {

            if (!$supplier) {
                $this->error(__('该供应商不存在，请重新选择'));
            }

        } else {
            // 查询退货订单信息
            $back = $this->BackModel->with(['business'])->where(['storageid' => $row['id']])->find();

            if (!$back) {
                $this->error('退货单不存在');
            }
        }
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            // halt($params);
            // 接收添加的商品数据，json字符串转成数组
            $productList = json_decode($params['product'], true);
            // halt($productList);
            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();
            // 封装入库数据
            $storageData = [
                'id' => $row['id'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => $row['status'],
            ];
            if ($row['type'] == 1) {
                $storageData['supplierid'] = $params['supplierid'];
            }
            if ($supplier) {
                // halt(123);
                $storageStatus = $this->model->validate('common/Depot/Storage.edit')->isUpdate(true)->save($storageData);
            } else {
                $storageStatus = $this->model->validate('common/Depot/Storage.backedit')->isUpdate(true)->save($storageData);
            }
            if ($storageStatus === FALSE) {
                $this->error($this->model->getError());
                exit;
            }

            // 存放封装好的商品数据
            $ProductData = [];
            // 封装一个在修改时新增的商品
            $NewProData = [];
            foreach ($productList as $item) {
                if (isset($item['id'])) {
                    $ProductData[] = [
                        'id' => $item['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                } else {
                    $NewProData[] = [
                        'id' => $item['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }
            }
            $delproid = json_decode($params['delproid']);
            // 删除不需要的商品
            if (!empty($delproid)) {
                $DelStatus = $this->DepotProductModel->destroy($delproid);
                if ($DelStatus === FALSE) {
                    $this->model->rollback();
                    $this->error($this->DepotProductModel->getError());
                    exit;
                }
            }
            $NewProStatus = $this->DepotProductModel->validate('common/Depot/Product')->saveAll($NewProData);
            $ProductStatus = $this->DepotProductModel->validate('common/Depot/Product.edit')->isUpdate(true)->saveAll($ProductData);
            if ($ProductStatus === FALSE || $NewProStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
                exit;
            }
            if ($ProductStatus === FALSE || $storageStatus === FALSE || $NewProStatus === FALSE) {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error('编辑失败');
                exit;
            } else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success('编辑成功');
                exit;
            }
        }
        // 商品的数据
        $productData = [];
        foreach ($ProductList as $item) {
            $product = $this->ProductModel->with(['type', 'unit'])->find($item['proid']);
            // halt($product->toArray());
            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];
        }
        $data = [
            'row' => $row,
            'supplier' => $supplier
        ];
        if (!$supplier) {
            $data['back'] = $back;
        }
        $this->assignconfig('Product', ['productData' => $productData]);
        return $this->view->fetch('', $data);
    }
    public function detail($ids = null)
    {
        $row = $this->model->find($ids);
        $supplier = $this->SupplierModel->with(['provinces', 'citys', 'districts'])->where('id', $row['supplierid'])->find();
        $ProductList = $this->DepotProductModel->where('storageid', $row['id'])->select();
        $productData = [];
        foreach ($ProductList as $item) {
            $product = $this->ProductModel->with(['type', 'unit'])->find($item['proid']);
            // var_dump($product);
            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];
        }
        // halt(collection($productData)->toArray());
        // exit;
        // halt($supplier->toArray());
        $this->view->assign([
            'row' => $row,
            'supplier' => $supplier,
            'productData' => $productData,
        ]);
        return $this->view->fetch();
    }
    /**
     * 入库审核
     */
    public function process()
    {
        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $status = $this->request->param('status');
            $data = [];
            if ($status == 1) {
                $data = [
                    'id' => $ids,
                    'status' => 2,
                    'reviewerid' => $this->auth->id
                ];
            } else {
                $data = [
                    'id' => $ids,
                    'status' => 1,
                    'reviewerid' => $this->auth->id
                ];
            }
            $result = $this->model->isUpdate(true)->save($data);
            if ($result === FALSE) {
                $this->error('审批失败');
                exit;
            } else {
                $this->success();
                exit;
            }
        }
    }
    /**
     * 撤回审核
     */
    public function cancel($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->find($ids);
            if (!$row) {
                $this->error(__('该入库不存在，请重新选择'));
            }
            $data = [
                'id' => $ids,
                'status' => 0,
                'reviewerid' => $this->auth->id
            ];
            $result = $this->model->isUpdate(true)->save($data);
            if ($result === FALSE) {
                $this->error('撤销审批失败');
                exit;
            } else {
                $this->success('撤销审批成功');
                exit;
            }
        }
    }
    /**
     * 确认入库
     */
    public function storage()
    {
        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $ProductList = $this->DepotProductModel->where('storageid', $ids)->select();
            // 开启事务
            $this->model->startTrans();
            $this->ProductModel->startTrans();

            // 更新入库表的数据
            $data = [
                'id' => $ids,
                'status' => 3,
                'adminid' => $this->auth->id
            ];
            $result = $this->model->isUpdate(true)->save($data);
            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            }
            // 封装更新库存
            $ProductData = [];
            // 遍历商品
            foreach ($ProductList as $item) {
                $product = $this->ProductModel->find($item['proid']);

                if ($product['id'] == $item['proid']) {
                    $ProductData[] = [
                        'id' => $product['id'],
                        'stock' => bcadd($product['stock'], $item['nums'])
                    ];
                }
            }
            $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);
            if ($ProductStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }
            if ($result === FALSE || $ProductStatus === FALSE) {
                $this->model->rollback();
                $this->ProductModel->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            } else {
                $this->model->commit();
                $this->ProductModel->commit();
                $this->success('入库成功');
                exit;
            }
        }
    }
    /**
     * 软删除
     */
    public function del($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->where(['id' => ['in', $ids]])->select();

            if (empty($row)) {
                $this->error(__('请选择需要删除入库单'));
            }

            $result = $this->model->destroy($ids);

            if ($result === FALSE) {
                $this->error(__('删除入库单失败'));
            } else {
                $this->success();
            }
        }
    }
    /**
     * 回收站
     */
    public function recyclebin()
    {
        // $total = $this->model->onlyTrashed()->select();
        // halt(collection($total)->toArray());
        // exit;
        // $list = $this->model->select();
        // halt(collection($list)->toArray());
        // exit;
        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            // if ($this->request->request('keyField')) {
            //     return $this->selectpage();
            // }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

    public function restore($ids = null)
    {
        $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

        if(!$row)
        {
            $this->error(__('请选择需要还原记录'));
        }

        $result = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->update(['deletetime' => null]);

        if($result != true)
        {
            $this->error(__('还原失败'));
        }else{
            $this->success();
        }
    }

    /**
     * 真实删除
    */
    public function destroy($ids = null)
    {
        if($this->request->isAjax())
        {
            Db::startTrans();

            try {
                $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

                if(empty($row))
                {
                    throw new Exception(__("请选择需要删除入库单"));
                }

                $StorageProduct = $this->DepotProductModel->where(['storageid' => ['in',$ids]])->column('id');

                $StorageStatus = $this->model->destroy($ids,true);

                if($StorageStatus === FALSE)
                {
                    throw new Exception(__($this->model->getError()));
                }

                $ProductStatus = $this->DepotProductModel->destroy($StorageProduct);

                if($ProductStatus === FALSE)
                {
                    throw new Exception(__($this->DepotProductModel->getError()));
                }

                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error(__($e->getMessage()));
            }

            $this->success();
        }
    }
}